# @Time    : 2022/10/18 15:57
# @Author  : ysh
# @File    : raw_sql
# @Software: PyCharm

import aiomysql
from conf.config import Config
# 配置文件选择器


async def sql_get_data(sql_text, args=None, is_cancle_full_only_mode=False, need_return_field=False):
    """
    查询数据
    :param sql_text: sql 语句
    :param args: 是否需要参数
    :param is_cancle_full_only_mode: 是否需要禁用 full_only_mode
    :param need_return_field: 是否需要返回字段名
    :return:
    """
    __pool = await aiomysql.create_pool(**{
            "host": Config.mysql.link["read"].host,
            "user": Config.mysql.link["read"].user,
            "password": Config.mysql.link["read"].password,
            "db": Config.mysql.link["read"].db_name,
            "port": Config.mysql.link["read"].port,
            "charset": 'utf8mb4',
            "pool_recycle": Config.mysql.pool_recycle,
            "connect_timeout": Config.mysql.connect_timeout,
        })
    async with __pool.acquire() as conn:
        cur = await conn.cursor(aiomysql.DictCursor)
        if is_cancle_full_only_mode:
            await cur.execute("""
                            set sql_mode ='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
                            """)
            await cur.commit()
        if args:
            await cur.execute(sql_text, args)
        else:
            await cur.execute(sql_text)
        datas = await cur.fetchall()
    if not need_return_field:
        return datas
    else:
        return {
            'field': [field[0] for field in await cur.description],
            'data': datas
                }
